<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\validate\NoteValidate;
use think\Request;

/**
 * 首页接口
 */
class Note extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['type','detailsshare'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = [];
    
    
    protected function _initialize(){
        parent::_initialize();
        $WeChatStatus = db('config')->where('name','WeChatStatus')->value('value');
        if($WeChatStatus)$this->error('微信小程序维护中...', null, 400400);
    }

    /**
     * 返回用户笔记列表
     *
     * @ApiMethod (POST)
     * @param string $page  分页码，非必填
     * @param string $key   关键字，非必填
    */
    public function list()
    {
        // 启用验证器
        (new NoteValidate())->goCheck('list');
        
        // 读取用户信息
        $user = $this->auth->getUser();
        
        // 从数据库查询用户的笔记
        $db = db('note')
            ->alias('a')
            ->join('note_type t','a.tid = t.id','LEFT')
            ->where([
                'a.uid'=>$user->id,
                'a.deletetime'=>null,
                'a.title|a.tags'=> ['like',"%".input('key')."%"]
            ])
            ->order('a.addtime', 'desc')
            ->field('a.id,a.title,a.tid,a.tags,a.note,a.url,a.addtime,t.name tname,t.id tid')
            ->paginate(10)
            ->each(function($item , $key) use ($user){
                // 检测标签是否存在
                if($item['tags']){
                    // 存在标签以逗号转数组
                    $item['tagsList'] = explode(',' , $item['tags']);
                }
                // 笔记内容截取长度
                $item['note'] = StringToText($item['note'],50);
                return $item;
            })
            ->toArray();
            
        // 成功响应
        $this->success(getReturnMsg($db),getListAjax($db));
    }

    /**
     * 笔记分类列表
     *
     * @ApiMethod (POST)
    */
    public function type()
    {

        $request = Request::instance();
        $domain = $request->domain();


        $db = db('note_type')
            ->where('status',1)
            ->order('weigh', 'desc')
            ->field('id,name,cover')
            ->select();


        foreach ($db as $key => $value) {
            $db[$key]['cover'] = $domain . $db[$key]['cover'];
        }
        
        $this->success('获取成功',$db);
    }


    /**
     * 返回用户标签笔记列表
     *
     * @ApiMethod (POST)
     * @param string $page  分页码，非必填
     * @param string $key   关键字，非必填
    */
    public function taglist()
    {
        // 读取用户信息
        $user = $this->auth->getUser();
        
        // 启用验证器
        (new NoteValidate())->goCheck('list');
        
        // 查询列表
        $db = db('note')
            ->alias('a')
            ->join('note_type t','a.tid = t.id','LEFT')
            ->where([
                'a.uid'=>$user->id,
                'a.deletetime'=>null,
                'a.tags'=> ['like',"%".input('key')."%"]
            ])
            ->order('a.addtime', 'desc')
            ->field('a.id,a.title,a.tid,a.tags,a.note,a.url,a.addtime,t.name tname,t.id tid')
            ->paginate(10)
            ->each(function($item , $key) use ($user){
                // 检测标签是否存在
                if($item['tags']){
                    // 存在标签以逗号转数组
                    $item['tagsList'] = explode(',' , $item['tags']);
                }
                // 笔记内容截取长度
                $item['note'] = StringToText($item['note'],50);
                return $item;
            })
            ->toArray();
        // 成功响应
        $this->success(getReturnMsg($db),getListAjax($db));
    }


    /**
     * 返回用户分类笔记列表
     *
     * @ApiMethod (POST)
     * @param string $page  分页码，非必填
     * @param string $id    分类ID，必填
    */
    public function typelist()
    {
        // 读取用户信息
        $user = $this->auth->getUser();
        
        // 启用验证器
        (new NoteValidate())->goCheck('type');
        
        // 接收请求参数
        $params = request()->param();

        // 查询列表
        $db = db('note')
            ->alias('a')
            ->join('note_type t','a.tid = t.id','LEFT')
            ->where([
                'a.uid'=>$user->id,
                'a.deletetime'=>null,
                'a.tid'=> $params['id']
            ])
            ->order('a.addtime', 'desc')
            ->field('a.id,a.title,a.tid,a.tags,a.note,a.url,a.addtime,t.name tname,t.id tid')
            ->paginate(10)
            ->each(function($item , $key) use ($user){
                // 检测标签是否存在
                if($item['tags']){
                    // 存在标签以逗号转数组
                    $item['tagsList'] = explode(',' , $item['tags']);
                }
                // 笔记内容截取长度
                $item['note'] = StringToText($item['note'],50);
                return $item;
            })
            ->toArray();
        // 成功响应
        $this->success(getReturnMsg($db),getListAjax($db));
    }


    
    /**
     * 获取用户分享的笔记列表
     *
     * @ApiMethod (POST)
     * @param string $page  分页码，非必填
    */
    public function sharelist()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('sharelist');

        // 查询列表
        $db = db('note_share')
            ->alias('a')
            ->join('note n','a.nid = n.id','LEFT')
            ->where('a.uid',$user->id)
            ->order('a.addtime', 'desc')
            ->field('a.*,n.title note_title,n.id nid,a.id id,a.addtime addtime')
            ->paginate(10)
            ->each(function($item , $key){
                // 封面检测
                $item['cover'] = $this->auth->setHttpUrl($item['cover']);
                // 检测是否过期
                $item['expired'] = ($item['sharetime'] - time())<=0?false:true;
                return $item;
            })
            ->toArray();
        // 成功响应
        $this->success(getReturnMsg($db),getListAjax($db));
    }


    /**
     * 删除分享记录
     *
     * @ApiMethod (POST)
     * @param string $id  必填
    */
    public function delshare()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('deleteShare');
        
        // 接收请求参数
        $params = request()->param();

        // 查询需要删除的数据是否存在
        $data = db('note_share')->where([
            'id'    =>  $params['id'],
            'uid'   =>  $user->id
        ])->find();
        
        // 检查是否查找到内容了
        if($data){
            $db = db('note_share')->where([
                'id'    =>  $params['id'],
                'uid'   =>  $user->id
            ])
            ->delete();
            return $this->success('删除成功');
        }
        
        return $this->error('对不起没有找到此条记录');
        
    }


    /**
     * 删除笔记
     *
     * @ApiMethod (POST)
     * @param string $id  必填
    */
    public function delnote()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('deleteNote');
        
        // 接收请求参数
        $params = request()->param();
        
        // 查询需要删除的数据是否存在
        $data = db('note')->where([
            'id'    =>  $params['id'],
            'uid'   =>  $user->id,
            'deletetime'=>null
        ])->find();
        
        // 检查是否查找到内容了
        if($data){
            $db = db('note')->where([
                'id'    =>  $params['id'],
                'uid'   =>  $user->id
            ])
            ->update([
                'deletetime'=>time()
            ]);
            return $this->success('删除成功');
        }
        
        return $this->error('对不起没有找到此条记录');
        
    }


    /**
     * 删除笔记中的账号
     *
     */
    public function deleteuser()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('deleteNote');
        
        // 接收请求参数
        $params = request()->param();

        $data = db('note_user')->where([
            'id'    =>  $params['id'],
            'uid'   =>  $user->id
        ])->find();
        
        // 检查是否查找到内容了
        if($data){
            $db = db('note_user')->delete($data['id']);
            if($db){
                return $this->success('删除成功');
            }else{
                return $this->error('删除失败');
            }
        }
        
        return $this->error('对不起没有找到此条记录');
        
    }

    /**
     * 笔记详情
     *
     * @ApiMethod (POST)
     * @param string $id  必填
    */
    public function details()
    {
        $Parsedown = new Parsedown();
        
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('note');
        
        // 接收请求参数
        $params = request()->param();

        // 查询笔记
        $data = db('note')
        ->alias('a')
        ->join('note_type t','a.tid = t.id','LEFT')
        ->where([
            'a.id'    =>  $params['id'],
            'a.uid'   =>  $user->id,
            'a.deletetime'=>null
        ])
        ->field('a.id,a.title,a.tid,a.tags,a.note,a.url,a.addtime,t.name tname')
        ->find();

        // 检查是否查询到了笔记
        if($data){
            // 检查标签是否存在
            if($data['tags']){
                $data['tagsList'] = explode(',' , $data['tags']);
            }
            
            // $data['note'] = $Parsedown->text(htmlspecialchars_decode($data['note']));
            
            $data['note'] = htmlspecialchars_decode($data['note']);
            
            // 查询笔记附加账号列表
            $data['userlist'] = db('note_user')->where([
                'nid'    =>  $params['id'],
                'uid'   =>  $user->id
            ])
            ->paginate(100)
            ->each(function($item , $key){
                // 密码解密
                $item['password'] = encrypt($item['password'], 'D', config('keyuser'));
                // 账号解密
                $item['username'] = encrypt($item['username'], 'D', config('keyuser'));
                return $item;
            });
            // 查询笔记分享记录列表
            $data['sharelist'] = db('note_share')
            ->alias('a')
            ->join('note n','a.nid = n.id','LEFT')
            ->where([
                'a.nid'    =>  $params['id'],
                'a.uid'   =>  $user->id
            ])
            ->order('a.addtime', 'desc')
            ->field('a.*,n.title note_title,n.id nid,a.id id')
            ->paginate(10)
            ->each(function($item , $key){
                // 封面检测
                $item['cover'] = $this->auth->setHttpUrl($item['cover']);
                // 检测是否过期
                $item['expired'] = ($item['sharetime'] - time())<=0?false:true;

                return $item;
            })
            ->toArray();
            
            // 查询可用的分享封面
            $shareCover = db('attachment')->where('category','custom')->orderRaw('rand()')->limit(8)->field('url,id')->select();
            
            $data['sharecover'] = [];
            
            // 处理数据格式
            foreach ($shareCover as $key => $value) {
                array_push($data['sharecover'],[
                    'id' => $value['id'],
                    'cover' => $this->auth->setHttpUrl($value['url']),
                    'url' => $value['url']
                ]);
            }

            return $this->success('获取成功',$data);
        }

        
        return $this->error('获取失败');
        
    }



    /**
     * 分享笔记详情
     *
     * @ApiMethod (POST)
     * @param string $id  必填
     * @param string $code  必填
    */
    public function detailsshare()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 启用验证器
        (new NoteValidate())->goCheck('noteShare');
        
        // 接收请求参数
        $params = request()->param();
        
        if(!input('id'))return $this->error('分享不存在');
        
        // 查询分享是否存在
        $db = db('note_share')->where([
            'share_id'  => input('id')
        ])->find();
        
        // 分享不存在
        if(!$db)return $this->error('分享不存在');
        
        // 查询分享码是否正确
        if($db['code']==$params['code']){
            // 查询分享是否过期了 
            if($db['sharetime'] < time())return $this->error('过期了',0);
        }else{
            // 分享码错误
            return $this->error('分享码错误');
        }
        
        // 查询笔记内容
        $note = db('note')
            ->where([
                'id'=>$db['nid'],
                'deletetime'=>null
            ])
            ->field('url,id,title,note')
            ->find();
        
        // 笔记内容处理
        if($note){
            $userlist = db('note_user')->where('nid',$note['id'])->field('username,password,title,note')->select();
            foreach ($userlist as $key => $value) {
                $userlist[$key]['password'] = encrypt($value['password'], 'D', config('keyuser'));
                $userlist[$key]['username'] = encrypt($value['username'], 'D', config('keyuser'));
            }
            $note['note'] = htmlspecialchars_decode($note['note']);
            $note['userlist'] = $userlist;
            return $this->success('获取成功',$note);
        }

        return $this->error('分享的笔记不存在了',$note);
        
    }


    /**
     * 创建笔记分享
     *
     * @ApiMethod (POST)
     * @param string $id    笔记ID，必填
     * @param string $title 分享标题，必填
     * @param string $cover 分享封面，必填
     * @param string $time  分享天数，必填
    */
    public function addnoteshare()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 接收请求参数
        $params = request()->param();
        
        // 启用验证器
        (new NoteValidate())->goCheck('addShare');
        
        // 查询笔记
        $data = db('note')->where([
            'id'    =>  $params['id'],
            'uid'   =>  $user->id,
            'deletetime'=>null
        ])->find();
        
        // 检查是否查找到内容了
        if($data){
            $insertGetId = db('note_share')->insertGetId([
                'title'     => $params['title'],
                'cover'     => $params['cover']?$params['cover']:'/assets/img/share.jpg',
                'sharetime' => time() + ($params['time']*86400),
                'addtime'   => time(),
                'nid'       => $params['id'],
                'uid'       => $user->id,
                'code'      => randomkeys(4),
                'share_id'  => $this->createShareId()
            ]);
            $share = db('note_share')->where('id',$insertGetId)->find();
            
            // 封面检测
            $share['cover'] = $this->auth->setHttpUrl($share['cover']);
            return $this->success('创建成功',$share);
        }
        
        return $this->error('该笔记不存在');
        
    }


    // 生成分享ID
    public function createShareId(){

        // 生成8位数识别码
        $code = $this->auth->make_code(20);
        // 判断是否存在
        $status = db('note_share')->where('share_id',$code)->find();

        // 判断识别码是否已经存在于数据库
        while ($status) {
            // 生成8位数识别码
            $code = $this->auth->make_code(20);
            // 继续判断是否存在于数据库
            $status = db('note_share')->where('share_id',$code)->find();
        }

        // 返回唯一性的识别码
        return $code;

    }

    /**
     * 添加笔记
     *
     */
    public function noteadd()
    {
        // 读取用户信息
        $user = $this->auth->getUser();
        
        // 启用验证器
        (new NoteValidate())->goCheck('addNote');

        // 接收请求参数
        $params = request()->param();

        // 转换账号记录
        $userlistData = json_decode(str_replace('&quot;','"',$params['userlist']),true);

        $type = db('note_type')->where('id',$params['tid'])->find();

        if($type){
            if($type['status']!=1)$this->error('不允许发布的分类');
        }

        // 如果分类不存在则使用默认分类
        if(!$type)$params['tid'] = 1;
        
        $resdata = [
            'title'     => $params['title'],
            'tid'       => $params['tid'],
            'tags'      => $params['tags'],
            'note'      => $params['note'],
            'uid'       => $user->id,
            'url'       => $params['url'],
            'addtime'   => time()
        ];

        $resdata['id'] = db('note')->insertGetId($resdata);

        $userlist = [];
        // 检测账号是否存在
        if($userlistData){
            // 进行加密
            foreach ($userlistData as $key => $value) {
                array_push($userlist,[
                    'username'  =>encrypt($value['username'], 'E', config('keyuser')),
                    'password'  =>encrypt($value['password'], 'E', config('keyuser')),
                    'title'     =>$value['title'],
                    'note'      =>$value['note'],
                    'uid'       =>$user->id,
                    'nid'       =>$resdata['id'],
                    'addtime'   =>time()
                ]);
            }
            $resdata['userlist'] = db('note_user')->insertAll($userlist);
        }

        return $this->success('创建成功',$resdata);
    }



     /**
     * 修改笔记
     *
     */
    public function noteedit()
    {
        // 读取用户信息
        $user = $this->auth->getUser();

        // 接收请求参数
        $params = request()->param();
        
        
        // 转换账号记录
        $userlistData = json_decode(str_replace('&quot;','"',$params['userlist']),true);

        $type = db('note_type')->where('id',$params['tid'])->find();

        if($type){
            if($type['id'] != $params['tid']){
                if($type['status']!=1)$this->error('不允许发布的分类');
            }
        }

        // 如果分类不存在则使用默认分类
        if(!$type)$params['tid'] = 1;
        
        $resdata = [
            'title'     => $params['title'],
            'tid'       => $params['tid'],
            'tags'      => $params['tags'],
            'note'      => $params['note'],
            'url'       => $params['url']
        ];

        $noteData = db('note')->where([
            'id'    =>  $params['id'],
            'uid'   =>  $user->id,
            'deletetime'=>null
        ])->find();

        // 检查要修改的笔记是否存在
        if($noteData){
            db('note')->where([
                'id'    =>  $params['id'],
                'uid'   =>  $user->id,
                'deletetime'=>null
            ])->update($resdata);
        }

        // 检测账号是否存在
        if($userlistData){
            // 遍历操作
            foreach ($userlistData as $key => $value) {

                // 有ID是修改
                if(array_key_exists('id',$value)){
                    
                    db('note_user')->where([
                        'nid'   =>  $params['id'],
                        'uid'   =>  $user->id,
                        'id'    =>  $value['id']
                    ])->update([
                        'username'  =>encrypt($value['username'], 'E', config('keyuser')),
                        'password'  =>encrypt($value['password'], 'E', config('keyuser')),
                        'title'     =>$value['title'],
                        'note'      =>$value['note']
                    ]);

                }else{

                    // 没有ID是新增
                    db('note_user')->insert([
                        'username'  =>encrypt($value['username'], 'E', config('keyuser')),
                        'password'  =>encrypt($value['password'], 'E', config('keyuser')),
                        'title'     =>$value['title'],
                        'note'      =>$value['note'],
                        'uid'       =>$user->id,
                        'nid'       =>$params['id'],
                        'addtime'   =>time()
                    ]);
                }
            }
        }

        return $this->success('创建成功',$resdata);
    }
    
}
